const chart = {
	/**
	 * 初始化
	 */
	init: function () {
		this.state = {
			originData: [], // 原始数据
			renderData: [], // 渲染数据
			typesData: [], // 户型种类
			blocksData: [],  // 楼栋种类
			floorsData: [],  // 楼层种类
			purposesData: [],  // 用途种类
			top: false, // 是否展示TOP100
			type: '不限',
			block: '不限',
			floor: '不限',
			purpose: '不限',
			myChart: echarts.init(document.getElementById('chart')),
			typeInfo: [
				{
					name: 'B6',
					area: 127,
					size: '三房两卫'
				},
				{
					name: 'B7',
					area: 117,
					size: '三房两卫'
				},
				{
					name: 'B8',
					area: 114,
					size: '三房两卫'
				},
				{
					name: 'B1',
					area: 108,
					size: '三房两卫'
				},
				{
					name: 'B2',
					area: 133.45,
					size: '四房两卫'
				},
				{
					name: 'B3',
					area: 125.57,
					size: '四房两卫'
				},
				{
					name: 'A1',
					area: 83,
					size: '两房一卫'
				},
				{
					name: 'A2',
					area: 86,
					size: '两房一卫'
				},
				{
					name: 'A5',
					area: 126,
					size: '四房两卫'
				},
				{
					name: 'B5',
					area: 132,
					size: '三房两卫'
				}
			]
		}
		const sUserAgent = navigator.userAgent.toLowerCase();
		const bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
		const bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
		const bIsMidp = sUserAgent.match(/midp/i) == "midp";
		const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
		const bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
		const bIsAndroid = sUserAgent.match(/android/i) == "android";
		const bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
		const bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
		if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
			alert("未做移动端适配，建议换用PC访问");
		} 
		this.getData();
	},
	/**
	 * 根据总面积，获取户型编号
	 */
	getType(acreage) {
		let type = '';
		const dealNum = parseInt(acreage, 10);
		if (parseFloat(acreage, 10) === 126.94) {
			type = 'B6'
		} else if (parseFloat(acreage, 10) === 112.54 || parseFloat(acreage, 10) === 112.28) {
			type = 'B7';
		} else if (parseFloat(acreage, 10) === 112.04 || parseFloat(acreage, 10) === 111.78) {
			type = 'B8'
		} else if (dealNum === 107 || dealNum === 108 || dealNum === 106) {
			type = 'B1';
		} else if (dealNum === 130 || dealNum === 129) {
			type = 'B2';
		} else if (dealNum === 126) {
			type = 'B3';
		} else if (dealNum === 82) {
			type = 'A1';
		} else if (dealNum === 85) {
			type = 'A2';
		} else if (dealNum === 123) {
			type = 'A5';
		} else if (dealNum === 131) {
			type = 'B5';
		} else {
			console.error(acreage)
		}
		return type;
	},
	/**
	 * 获取数据
	 */
	getData: function () {
		const self = this;
		d3.csv('data/data.csv', function (error, data) {
			if (error) {
				console.error(error);
			}
			self.state.originData = data;
			self.render();
		})
	},
	/**
	 * 渲染图表
	 */
	render: function () {
		this.renderTypes();
		this.renderBlocks();
		this.renderFloors();
		this.renderPurposes();
		this.filterData();
	},
	/**
	 * 渲染户型下拉列表
	 */
	renderTypes: function () {
		const { originData, typeInfo } = this.state;
		const types = [];
		let typesDom = `<option>不限</option>`;
		originData.forEach(d => {
			const type = this.getType(d.acreage);
			if (types.indexOf(type) === -1) {
				types.push(type);
			}
		})
		this.state.typesData = types;
		types.forEach(d => {
			const info = typeInfo.filter(detail => detail.name === d)[0];
			typesDom += `<option>${d},${info.size},面积约${info.area}/㎡</option>`;
		})
		$('.types-list').html(typesDom);
	},
	/**
	 * 渲染楼栋下拉列表
	 */
	renderBlocks: function () {
		const { originData } = this.state;
		const blocks = [];
		let blocksDom = `<option>不限</option>`;
		originData.forEach(d => {
			if (blocks.indexOf(parseInt(d.block, 10)) === -1) {
				blocks.push(parseInt(d.block, 10));
			}
		})
		const renderBlocks = blocks.sort((a, b) => a - b);
		this.state.blocksData = renderBlocks;
		renderBlocks.forEach(function (d) {
			blocksDom += `<option>${d}</option>`;
		})
		$('.blocks-list').html(blocksDom);
	},
	/**
	 * 渲染楼层下拉列表
	 */
	renderFloors: function () {
		const { originData } = this.state;
		const floors = [];
		let floorsDom = `<option>不限</option>`;
		originData.forEach(d => {
			if (floors.indexOf(parseInt(d.floor, 10)) === -1) {
				floors.push(parseInt(d.floor, 10));
			}
		})
		const renderFloors = floors.sort((a, b) => a - b)
		this.state.floorsData = renderFloors;
		renderFloors.forEach(function (d) {
			floorsDom += `<option>${d}</option>`;
		})
		$('.floors-list').html(floorsDom);
	},
	/**
	 * 渲染用途下拉列表
	 */
	renderPurposes: function () {
		const { originData } = this.state;
		const purposes = [];
		let purposesDom = `<option>不限</option>`;
		originData.forEach(d => {
			if (purposes.indexOf(d.purpose) === -1) {
				purposes.push(d.purpose);
			}
		})
		this.state.purposesData = purposes;
		purposes.forEach(function (d) {
			purposesDom += `<option>${d}</option>`;
		})
		$('.purposes-list').html(purposesDom);
	},
	/**
	 * 过滤数据
	 */
	filterData: function () {
		const { type, block, floor, purpose, top, originData } = this.state;
		// 按照 type, block, floor 筛选
		let data = originData.filter(typeData => {
			return type === '不限' || this.getType(typeData.acreage) === type;
		}).filter(blockData => {
			return block === '不限' || blockData.block === block;
		}).filter(floorData => {
			return floor === '不限' || floorData.floor === floor;
		}).filter(purposeData => {
			return purpose === '不限' || purposeData.purpose === purpose;
		})

		data.sort((a, b) => parseFloat(a.decorate, 10) - parseFloat(b.decorate, 10));

		if (top && data.length > 100) {
			data = data.slice(-100, data.length)
		}
		this.state.renderData = data;
		this.renderChart();
	},
	/**
	 * 绘制折线图
	 */
	renderChart: function () {
		const { renderData, myChart } = this.state;
		const xData = [];
		const yData = [];
		renderData.forEach((d, i) => {
			xData.push(i + 1);
			yData.push(parseFloat(d.decorate));
		})
		const option = {
			tooltip: {
				formatter: function (params) {
					const data = renderData[params.dataIndex];
					const sf = (parseFloat(data.decorate, 10) * 0.3).toFixed(2);
					return `基本信息: ${data.block}栋${data.unit}单元第${data.floor}层<br/>房号：${data.room}<br/>套内面积：${data.area}/㎡<br/>公摊面积：${data.public}/㎡<br/>总面积：${data.acreage}/㎡<br/>规划用途：${data.purpose}<br/>装修申报价：${data.decorate}/万元<br/>首付三成：${sf}/万元`
				}
			},
			xAxis: {
				type: 'category',
				data: xData,
				axisTick: {
					alignWithLabel: true
				}
			},
			yAxis: [{
				type: 'value'
			}],
			series: [{
				type: 'bar',
				data: yData,
				itemStyle: {
					color: '#3398DB'
				},
				animationDelay: idx => {
					return idx * 0.8;
				}
			}],
			animationEasing: 'elasticOut',
			animationDelayUpdate: idx => {
				return idx * 0.6;
			}
		};
		myChart.setOption(option);

		this.bindEvent(); // 图表绘制完成，绑定事件
	},
	/**
	 * 绑定图表事件
	 */
	bindEvent: function () {
		const self = this;
		$('.types-list').off().on('change', () => {
			const type = $('.types-list').val().slice(0, 2);
			self.state.type = type;
			self.filterData();
		})
		$('.blocks-list').off().on('change', () => {
			const block = $('.blocks-list').val();
			self.state.block = block;
			self.filterData();
		})
		$('.floors-list').off().on('change', () => {
			const floor = $('.floors-list').val();
			self.state.floor = floor;
			self.filterData();
		})
		$('.purposes-list').off().on('change', () => {
			const purpose = $('.purposes-list').val();
			self.state.purpose = purpose;
			self.filterData();
		})

		$('.top-btn').off().on('click', function() {
			self.state.top = !self.state.top;
			$(this).toggleClass('btn-success')
			self.filterData()
		})


	}
}
